<?php

namespace App\Http\Controllers;

use App\Models\News;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;
use Carbon\Carbon;

class NewsController extends Controller
{
    /**
     * Display a listing of the resource.
     */
    public function index(Request $request)
    {
        $page = $request->input('page', 1);
        $size = $request->input('size', 10);
        $news = News::where('isdelete', 0)->paginate($size, ['*'], 'page', $page);
        if ($news->isEmpty()) return response()->json(['code' => 201, 'msg' => '查询失败']);
        return response()->json([
            "code" => 200,
            "list" => $news->items(),
            "msg" => "查询成功",
            "page" => $news->currentPage(),
            "size" => $news->perPage(),
            "total" => $news->total()
        ]);
    }
    /**
     * Store a newly created resource in storage.
     */
    public function store(Request $request)
    {
        $file = $request->file('file');
        if($file) {
            $url = $request->input('loginname') . rand(1,9999) . $file->getClientOriginalName();
            $file->storeAs('img', $url, 'public');
            $imageUrl = asset('storage/img/' . $url);
        } else {
            $imageUrl = '';
        }
        News::insert([
            'newstitle' => $request->input('newstitle'),
            'image' => $imageUrl,
            'newscontent' => $request->input('newscontent'),
            'loginname' => $request->input('loginname'),
            'isdelete' => 0,
            'readcount' => 0,
            'collect' => 0,
            'newstype' => 0,
            'created_at'=>Carbon::now(),
            'updated_at'=>Carbon::now(),
        ]);
        return response()->json(['code' => 200, 'msg' => '添加成功']);
    }

    /**
     * Display the specified resource.
     */
    public function show(string $id)
    {
        //
        $data = News::find($id);
        News::where('id','=',$id) -> update([
            'readcount' => $data->readcount + 1
        ]);
        return response()->json([
            'code' => 200,
            'data' => $data
        ], 200);
    }

    /**
     * Update the specified resource in storage.
     */
    public function update(Request $request, string $id)
    {
        //
        return response()->json([
            'code' => 200,
            'data' => $request -> all()
        ], 200);
    }

    /**
     * Remove the specified resource from storage.
     */
    public function destroy(Request $request,string $id)
    {
        //
        {
            $news = News::where('id', '=' , $id)->where('loginname', $request->input('token'))->first();
            if (empty($news)) {
                return response()->json(['code' => 201, 'msg' => '数据校验失败,您无权删除他人的文章']);
            } else {
                $news->isdelete = 1;
                $news->save();
                return response()->json(['code' => 200, 'msg' => '删除成功']);
            }
        }
    }
}
